#include "dataprocessor.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

DataProcessor::DataProcessor(QObject *parent) : QThread(parent), running(true)
{
}

DataProcessor::~DataProcessor()
{
    stop();
    wait();
}

void DataProcessor::addData(const AdData &data)
{
    QMutexLocker locker(&mutex);
    dataQueue.enqueue(data);
}

void DataProcessor::stop()
{
    running = false;
}

void DataProcessor::run()
{
    while (running) {
        QQueue<AdData> batch;
        
        // 获取一批数据
        {
            QMutexLocker locker(&mutex);
            while (!dataQueue.isEmpty() && batch.size() < BATCH_SIZE) {
                batch.enqueue(dataQueue.dequeue());
            }
        }
        
        // 如果有数据要处理
        if (!batch.isEmpty()) {
            // 批量插入数据库
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
            db.setDatabaseName("chaomu_data.db");
            
            if (db.open()) {
                QSqlQuery query;
                query.prepare("INSERT INTO ad_data (AD, pos, timestamp) VALUES (?, ?, ?)");
                
                db.transaction();
                while (!batch.isEmpty()) {
                    AdData data = batch.dequeue();
                    query.addBindValue(data.ad);
                    query.addBindValue(data.pos);
                    query.addBindValue(data.timestamp);
                    query.exec();
                }
                db.commit();
                
                emit dataProcessed(batch.size());  // 发送信号通知处理完成
                qDebug() << "Batch processed:" << batch.size() << "records";
            }
        }
        
        msleep(10);
    }
} 